import requests
from urllib.parse import unquote
from urllib.parse import quote
import requests
from bs4 import BeautifulSoup

def get_title(url):


    # 目标网页的URL
    url = "https://www.nianyin.com/dushiyanqing/2029.html"  # 这里替换成你实际的网页地址，比如你提到的念音听书网对应页面的URL

    # 发送GET请求获取网页内容
    response = requests.get(url)
    # 使用BeautifulSoup解析网页内容，指定解析器为html.parser
    soup = BeautifulSoup(response.text, 'html.parser')
    # 通过title标签来获取标题内容
    title = soup.title.string.split('_')[-2]
    book_name = title.replace("全集","")
    print(book_name)
    return book_name

def download(title,count = 17):
    # 目标音频文件的URL
    # url = "https://oss-links.guoguo.org.cn/uploads/t008/17-%E8%AE%B8%E4%B8%89%E8%A7%82%E5%8D%96%E8%A1%80%E8%AE%B0/002.m4a"
    url = "https://oss-links.guoguo.org.cn/uploads/t008/"+str(count)+"-"+quote(title)+"/003.m4a"
    #
    # php_url = '/nyts.php?uid=t008/17-%E8%AE%B8%E4%B8%89%E8%A7%82%E5%8D%96%E8%A1%80%E8%AE%B0/001.m4a'

    # 对URL中的编码部分进行解码，以便更好地查看和处理路径信息
    decoded_url = unquote(url)

    # decoded_url = quote(url,safe=[':','/'])
    print(decoded_url)
    # decoded_php_url = unquote(php_url)
    # print(decoded_url)
    # print(decoded_php_url)

    headers =  {'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0', "Referer":'https://www.nianyin.com/'}
    try:
        # 发送HTTP GET请求获取音频文件内容
        response = requests.get(url,headers=headers)
        if response.status_code == 200:
            # 从URL中获取文件名
            file_name = decoded_url.split('/')[-2]+decoded_url.split('/')[-1]
            with open(file_name, 'wb') as file:
                file.write(response.content)
                print(f"音频文件 {file_name} 下载成功！")
        else:
            print(f"请求失败，状态码: {response.status_code}")
            print(response.headers)
    except requests.exceptions.RequestException as e:
        print(f"请求出错: {e}")

# get_title("https://www.nianyin.com/dushiyanqing/2029.html"
# )
# print(quote(get_title("https://www.nianyin.com/dushiyanqing/2029.html"
#                 )))
download(title=get_title("https://www.nianyin.com/dushiyanqing/2029.html"),count=17)